﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EvidenceService.Core;
using NHibernate;

namespace EvidenceWeb
{
    public class NHSessionModule:IHttpModule
    {
        public void Dispose()
        {
            
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
            context.EndRequest += context_EndRequest;
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            ISessionFactory sessionFactory=HbmSessionUtil.GetHbmFactory();
            ISession session = sessionFactory.OpenSession();

            HttpContext.Current.Items.Add("HbmSession", session);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Items["HbmSession"] != null)
            {
                ISession session = HttpContext.Current.Items["HbmSession"] as ISession;

                if (session != null && session.IsOpen)
                {
                    session.Close();
                    session.Dispose();
                }
            }
        }
    }
}